<template>
	<uni-nav-bar fixed="true" statusBar="true" border="false" left-icon="left" title="钱包" @clickLeft="back"></uni-nav-bar>
	<view :style="{'padding-top':navTop+'px'}">
		<view class="fixed-top-wrap">
			<view class="uni-padding-wrap pb80">
				<view class="withdrawable box-shadow-grey8 boxsiz bor_r20 p40100">
					<view class="mt15 tc mb30 font_size_36 color-black">
						可提现金额
					</view>
					<view class="mb30 tc font_size_50 color-black">
						{{accountInfo.canUseBalance}}
					</view>
					<view class="">
						<button class="search_btn line-h50 color_green font_size_28" style="background-color: rgba(55, 182, 74, 0.3);border: none;" type="success" @tap="navgetTo('pages/my/wallet_withdrawal',accountInfo,'')">提现</button>
					</view>
				</view>
				<view class="tab">
					<text :class="navIndex==0?'mr100 active':'mr100'" @click="checkIndex(0)">收入明细</text><text :class="navIndex==1?'active':''" @click="checkIndex(1)">提现明细</text>
				</view>
				<view class="lh50 uni-flex ac sp_betw bor_b p100">
					<view class="">
						<view class="lineFlex">
							<picker mode="date" fields="month" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
								<view class="uni-input">{{date}}</view>
							</picker>
						</view>
						<uni-icons type="down" size="16" color="#666"></uni-icons>
					</view>
					<view class="">
						{{totalMoney}}
					</view>
				</view>
				</view>
				<view class="bottom_wrap">
					<view class="uni-padding-wrap pb80">
					<!-- 内容切换 -->
					<scroll-view scroll-y="true" scroll-x="false" :style="{height:scrollH+'px'}" refresher-enabled="true" :refresher-triggered="isRefreshing" @refresherrefresh="onRefresh" @scrolltolower="onLoadMore">
					<view class="content" v-if="navIndex==0 && List.length>0" v-for="item in List">
						<view class="bor_b p200">
							<view class="uni-flex w100 boxsiz uni-row sp_betw astre">
								<view class="flex1 lh50">
									<view class="mb10 tl font_size_26">{{item.incomeDesc}}</view>
								</view>
								<view class="lh50">
									<view class="mb10 tr font_size_42">+{{item.realAmount}}</view>
								</view>
							</view>
							<view class="uni-flex w100 boxsiz uni-row sp_betw astre">
								<view class="lh50">
									<view class="mb10 tl font_size_26">{{item.recordDate}}</view>
								</view>
								<view class="flex1 lh50">
									<view class="mb10 font_size_26 tr">实收￥{{item.incomeAmount}}扣除{{item.rate}}%服务费</view>
								</view>
							</view>
						</view>
					</view>
					<!-- 内容切换 -->
					<view class="content" v-if="navIndex==1 && List.length>0" v-for="item in List">
						<view class="uni-flex sp_betw ac bor_b p200">
							<view class="">
								<view class="mb10 font_size_26" v-if="item.withdrawStatus == 1">账户余额提现-待审核</view>
								<view class="mb10 font_size_26" v-if="item.withdrawStatus == 2">账户余额提现-打款中</view>
								<view class="mb10 font_size_26" v-if="item.withdrawStatus == 3">账户余额提现-已打款</view>
								<view class="mb10 font_size_26" v-if="item.withdrawStatus == 0">账户余额提现-已驳回</view>
								<view class="mb10 font_size_26">{{item.recordDate}}</view>
								<view class="mb10 font_size_26">{{item.refuseReason}}</view>
							</view>
							<view class="tr font_size_42">
								-{{item.withdrawAmount}}
							</view>
						</view>
					</view>
					<!-- 加载提示 -->
					 <view v-if="isLoading" class="tc mt100 mb100">{{loadMoreText}}</view>
					 </scroll-view>
					 </view>
				</view>
			</view>
	</view>
</template>
<script>
	import api from '@/common/api/webapi.js'; /*api*/
	import storageUtil from '@/common/util/storageUtil.js';
	export default {
		data() {
			const currentDate = this.getDate({
				format: true
			})
			return {
				navTop: 40,
				date:currentDate,
				startDate:this.getDate('start'),
				endDate:this.getDate('end'),
				totalIncome:'0.00',
				navIndex: 0,
				memberAccount:0,
				scrollH:0,
				isRefreshing:false,
				isLoading:false,
				loadMoreText:"加载中...",
				List:[],
				accountInfo:{},
				totalMoney:'',
				param: {
					page: 1, //当前页
					limit: 10, //每页显示记录数
					PageCount: 0,
					pageType:"HISTORY",
					keyword:"",
				},
			}	
		},
		onReady() {
			// 获取可滚动区域的高度：视口高度 - tabbar切换卡高度就是剩余的内容可滚动的。
			//如果你使用取消了原生导航栏，记着把你自定义导航栏的高度也减掉哦
			uni.getSystemInfo({
				success: (res) => {
					this.scrollH = res.windowHeight -351 - uni.upx2px(100)
				}
			})
		},
		onLoad(option) {
			const app = getApp()
			this.navTop = app.globalData.navTop;
			// 显示加载提示
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
			// 先获取账户信息，再获取列表数据，避免请求竞争
			this.GetDetailInfo().then(() => {
				this.checkIndex(0);
			});
		},
		methods: {
			back(){
				uni.switchTab({
					url:'/pages/my/my',
				});
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				if (type === 'start') {
					// 起始日期为当前月份的前一年
					if (month === 1) {
						year -= 1;
						month = 12;
					} else {
						month -= 12;
						if (month <= 0) {
							year -= 1;
							month += 12;
						}
					}
				} else if (type === 'end') {
					// 结束日期为当前月份
					// 保持当前年月不变
				}
				month = month > 9 ? month : '0' + month;
				return `${year}-${month}`;
			},
			bindDateChange: function(e) {
				this.date = e.detail.value;
				// 切换日期时显示加载提示
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				this.getPageList('onPullDownRefresh', this.navIndex);
			},
			checkIndex(index) {
				this.navIndex = index;
				this.param.page = 1;
				// 切换标签页时显示加载提示
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				this.getPageList('onPullDownRefresh', this.navIndex);
			},
			GetDetailInfo() {
				let _this = this;
				// 返回Promise以便在onLoad中控制请求顺序
				return new Promise((resolve) => {
					api.walletDetail().then(res => {
						if (res.code === 0) {
							_this.accountInfo = res.data;
						} else {
							uni.showToast({
								icon: 'none',
								title: '获取账户信息失败'
							});
						}
						resolve();
					}).catch(() => {
						uni.showToast({
							icon: 'none',
							title: '网络请求失败'
						});
						resolve();
					})
				});
			},
			onRefresh() {  // 下拉刷新
				this.isRefreshing = true;
				this.param.page = 1;
				this.getPageList('onPullDownRefresh',this.navIndex);
			},
			onLoadMore() {  // 上拉加载
				if (this.isLoading) return;
				this.isLoading = true;
				this.param.page = (this.param.page + 1);
				if (this.param.page > this.param.PageCount) {
					this.isLoading = true;
					this.loadMoreText = "--到底啦--"
					return;
				}
				this.getPageList('onReachBottom',this.navIndex);
			},
			// 获取分页列表
			getPageList(type, navIndex) {
				let _this = this;
				// 重置加载状态
				_this.isLoading = true;
				_this.loadMoreText = "加载中...";
				// 只有在下拉刷新时重置列表
				if (type === 'onPullDownRefresh') {
					// 使用Vue.set确保响应式更新
					this.$set(this, 'List', []);
				}
				
				// 从this.date中解析年和月，格式为YYYY-MM
				const dateParts = this.date.split('-');
				const year = parseInt(dateParts[0]);
				const month = parseInt(dateParts[1]);
				// 设置startDate为所选月份的第一天
				const startDate = `${year}-${month.toString().padStart(2, '0')}-01`;
				// 获取所选月份的最后一天作为endDate
				const lastDay = new Date(year, month, 0).getDate();
				const endDate = `${year}-${month.toString().padStart(2, '0')}-${lastDay.toString().padStart(2, '0')}`;
				
				let requestData = {
					params: { 
						page: _this.param.page, //当前页
						size: _this.param.limit, //每页显示记录数
						startDate: startDate,
						endDate: endDate,
					}
				}
				//入账明细
				if(navIndex == 0){
					api.incomeList(requestData).then(res => {
						// 隐藏加载提示
						uni.hideLoading();
						if (res.code === 0) {
							// 使用Vue.set确保响应式更新
							this.$set(this, 'totalMoney', `总收入￥${res.data.totalIncome}`);
							// 直接更新数据，不再使用setTimeout延迟
							if (res.data.walletIncomeDtoList && res.data.walletIncomeDtoList.length > 0) {
								let pagelist = res.data.walletIncomeDtoList;
								if (type == "onReachBottom") {
									// 先创建新数组，确保Vue能检测到变化
									const newList = [..._this.List, ...pagelist];
									this.$set(this, 'List', newList);
								} else {
									// 直接设置新数组
									this.$set(this, 'List', pagelist);
								}
							}else{
								this.$set(this, 'List', []);
							}
						} else {
							uni.showToast({
								icon: 'none',
								title: '获取收入明细失败'
							});
						}
					// 确保加载状态更新
					this.$nextTick(() => {
						this.$set(this, 'isRefreshing', false);
						this.$set(this, 'isLoading', false);
						this.$set(this, 'loadMoreText', "");
					});
					}).catch(function(){
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: '网络请求失败'
						});
						// 确保加载状态更新
						this.$nextTick(() => {
							this.$set(this, 'isRefreshing', false);
							this.$set(this, 'isLoading', false);
							this.$set(this, 'loadMoreText', "");
						});
					})
				}else if(navIndex == 1){
					api.withdrawList(requestData).then(res => {
						// 隐藏加载提示
						uni.hideLoading();
						if (res.code === 0) {
							// 使用Vue.set确保响应式更新
							this.$set(this, 'totalMoney', `总提现￥${res.data.totalWithdraw}`);
							// 修复数据字段名称不匹配问题
							// 直接更新数据，不再使用setTimeout延迟
							// 优先使用walletWithdrawDtoList，这是正确的数据字段名
							const dataList = res.data.walletWithdrawDtoList || res.data.walletIncomeDtoList || [];
							if (dataList.length > 0) {
								let pagelist = dataList;
								if (type == "onReachBottom") {
									// 先创建新数组，确保Vue能检测到变化
									const newList = [..._this.List, ...pagelist];
									this.$set(this, 'List', newList);
								} else {
									// 直接设置新数组
									this.$set(this, 'List', pagelist);
								}
							}else{
								if(type == "onPullDownRefresh"){
									this.$set(this, 'List', []);
								}else if(type == "onReachBottom"){
									this.$set(this, 'loadMoreText', "--到底啦--");
								}
							}
						} else {
							uni.showToast({
								icon: 'none',
								title: '获取提现明细失败'
							});
						}
					// 确保加载状态更新
					this.$nextTick(() => {
						this.$set(this, 'isRefreshing', false);
						this.$set(this, 'isLoading', false);
						if(type !== "onReachBottom"){
							this.$set(this, 'loadMoreText', "");
						}
					});
					}).catch(function(){
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: '网络请求失败'
						});
						// 确保加载状态更新
						this.$nextTick(() => {
							this.$set(this, 'isRefreshing', false);
							this.$set(this, 'isLoading', false);
							this.$set(this, 'loadMoreText', "");
						});
					})
				}
			},
			// 页面跳转
			navgetTo(page, param, type) {
				if (param != undefined) {
					type = type || '';
					let data = {
						data: param,
						page: type
					}
					uni.navigateTo({
						url: "/" + page + "?param=" + encodeURI(JSON.stringify(data))
					});
				} else {
					uni.navigateTo({
						url: "/" + page
					});
				}
			},
			// getProfitData(){
			// 	let _this = this;
			// 	let year = this.date.split("-")[0];
			// 	let month = this.date.split("-")[1];
			// 	let params = {
			// 		params:{
			// 			phone:uni.getStorageSync("phone"),
			// 			year:year,
			// 			month:month
			// 		}
			// 	}
			// 	uni.showLoading({
			// 		title: '加载中。。。',
			// 		mask:true,
			// 	})
			// 	api.getProfitData(params).then(res => {
			// 		if (res.code === 0) {
			// 			uni.hideLoading();
			// 			_this.incomeInfo = res.data;
			// 		} else {
			// 			uni.hideLoading();
			// 			uni.showToast({
			// 				icon: 'none',
			// 				title: res.msg
			// 			});
			// 		}
			// 	}).catch(e=>{
			// 		uni.hideLoading();
			// 	})
			// }
		}
	}
</script>

<style lang="scss">
	.withdrawable{
		width: 80%;
		margin: 40rpx auto;
	}
	.fixed-top-wrap{
		top: 80px;
	}

</style>
